//
//  MTFindVC.m
//  met
//
//  Created by 李晓俊 on 2019/5/6.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTFindVC.h"
#import "RightPhotoButton.h"
#import <CoreLocation/CoreLocation.h>
#import "MTScreenView.h"
#import "MTFindView.h"
#import "MTNewCardListVC.h"

#import "HighLightButton.h"
#import "MTQuestionAnswerVC.h"
#import "MTQuestionNpcAnswerVC.h"
#import "MTTicketVC.h"

#import "MTNewUserInfoVC.h"

#import "MTShouQuanVC.h"
#import "CYLMainRootViewController.h"
#import "MTStepVC.h"
#import "ChatViewController.h"
#import "MTShouhuView.h"

#import <UShareUI/UShareUI.h>
#import "MTYaoQingView.h"
#import <CoreMotion/CoreMotion.h>

#import "WNImagePicker.h"

#import "MTPubMarkVC.h"

#import "MTFindOtherVC.h"
#import "MTMarkDetailVC.h"
#import "MTNewCardFirstVC.h"

#import "ZLAdvertView.h"
#import "MTPiaoLiuView.h"
#import "MTDingWeiView.h"
#import "MTYinjiView.h"
@import Mapbox;
@interface MyCustomPointAnnotation : MGLPointAnnotation
@property (nonatomic, assign) BOOL willUseImage;
@property (nonatomic,strong) NSString *userId;
@property (nonatomic,strong) FindModel *model;
@end
@implementation MyCustomPointAnnotation
@end

@interface MyCustomYinjiPointAnnotation : MGLPointAnnotation
@property (nonatomic, assign) BOOL willUseImage;
@property (nonatomic,strong) NSString *userId;
@property (nonatomic,strong) YinjiModel *model;
@end
@implementation MyCustomYinjiPointAnnotation
@end

@interface MGLCustomAnnotationView : MGLAnnotationView
@property (nonatomic,strong) NSString *yinji;
@property (nonatomic,strong) UIImageView *bg;
@property (nonatomic,strong) UIImageView *img;
@end
@implementation MGLCustomAnnotationView
@end

@interface MTFindVC ()<MGLMapViewDelegate,CLLocationManagerDelegate,UMSocialShareMenuViewDelegate,WNImagePickerDelegate,EMClientDelegate,EMChatManagerDelegate>{
    CLLocationManager *manager;
}
@property (nonatomic,strong) MGLMapView *mapView;

@property (nonatomic, copy) NSArray *annotationsArray;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic,strong) NSString *jumpUrl;

@property (nonatomic,strong) CMPedometer *pedometer;

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIView *bgView2;

@property (nonatomic,strong) MTFindView *findView;
@property (nonatomic,strong) HighLightButton *refreshBut;
@property (nonatomic,strong) NSMutableArray *dataArr;
@property (nonatomic,strong) NSMutableArray *yinjiArr;

@property (nonatomic,strong) NSMutableArray *pointArr;

@property (nonatomic,strong) NSMutableArray *yinjipointArr;
@property (nonatomic,strong) NSMutableArray *myyinjipointArr;

@property (nonatomic,strong) FindModel *chooseModel;
@property (nonatomic,strong) MGLPointAnnotation *chooseAnnotation;
@property (nonatomic,strong) UIView *caozuoView;

@property (nonatomic,strong) HighLightButton *stepBut;
@property (nonatomic,strong) HighLightButton *piaoliuBut;

@property (nonatomic,strong) HighLightButton *backBut;
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,strong) UIView *findView2;
@property (nonatomic,strong) HighLightButton *siliaoBut;
@property (nonatomic,strong) HighLightButton *zhuyeBut;
@property (nonatomic,strong) HighLightButton *liaotaBut;

@property (nonatomic,strong) UIImageView *userImage;

@property(weak, nonatomic) id <EMClientDelegate> delegate;


@property (nonatomic,strong) MTDingWeiView *dingweiView;
@end

@implementation MTFindVC {
    UILabel *_codelabel;
    NSTimer *_timer;
    int   timeDown;
    NSTimer *_timer2;
    int   timeDown2;
}


- (void)dealloc {
    //移除消息回调
    [[EMClient sharedClient] removeDelegate:self ];
    [[EMClient sharedClient].chatManager removeDelegate:self];
}
//获取未读消息数量
- (void)getUnreadCount {
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger totalUnreadCount = 0;
    for (EMConversation *conversation in conversations) {
        totalUnreadCount += conversation.unreadMessagesCount;
    }
    if (totalUnreadCount > 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:MTMessageNotification object:nil];
    }
}
- (void)messagesDidReceive:(NSArray *)aMessages {
    [[NSNotificationCenter defaultCenter] postNotificationName:MTMessageNotification object:nil];
    for (EMMessage *message in aMessages) {
        Message *msg =  [[Message alloc] init];
        msg.userId = message.from;
        msg.username = [message.ext objectForKey:@"username"];
        msg.headImageUrl = [message.ext objectForKey:@"headImageUrl"];
        [Message insertObject:msg];
    }
    [self getUnreadCount];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self customNavItem];
    
   
    
    [self wr_setNavBarBackgroundAlpha:0];
     self.view.backgroundColor = KWhiteColor;
    
    NSString *zh = [NSString stringWithFormat:@"met_%@",KUSER.usersId];
    EMError *error = [[EMClient sharedClient] loginWithUsername:zh password:zh];
    if (!error) {
        DLog(@"登录成功");
        [[EMClient sharedClient].options setIsAutoLogin:YES];
    }
    self.delegate = self;
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
    
//    NSURL *url = [NSURL URLWithString:@"mapbox://styles/yuzhong/cjw7iyhct071f1clcotyh50uu"];
//    NSURL *url = [NSURL URLWithString:@"mapbox://styles/yuzhong/cjwxxkt0s35um1co5ay5dg4mh"];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.mapUrl]];
     _mapView = [[MGLMapView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, self.view.frame.size.height - TabbarHeight -5) styleURL:url];
    _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//    [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(39.9,116.4)
//                       zoomLevel:14
//                        animated:NO];
    _mapView.logoView.hidden = YES;
    _mapView.attributionButton.hidden = YES;
    
    _mapView.delegate = self;
    //是否旋转地图
    _mapView.rotateEnabled  = NO;
    _mapView.pitchEnabled  = NO;

    
    _mapView.userTrackingMode = MGLUserTrackingModeFollow;
    _mapView.showsUserHeadingIndicator = YES;
    //显示用户位置
    _mapView.showsUserLocation  = YES;
    
    manager = [[CLLocationManager alloc]init];
    manager.delegate = self;
    manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;//精准度
    manager.distanceFilter = 1.0;
    [manager startUpdatingLocation];
    [self.view addSubview:_mapView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushCard) name:MTCardNotification1 object:nil ];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushPhoto) name:MTPhotoNotification1 object:nil ];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshMap:) name:MTMapNotification object:nil ];

    
    [self setRefresh];
    [self setStep];
    [self setPiaoliu];
    self.dataArr = [NSMutableArray new];
    self.pointArr = [NSMutableArray new];
    self.yinjipointArr = [NSMutableArray new];
    self.myyinjipointArr = [NSMutableArray new];

    [UMSocialUIManager setShareMenuViewDelegate:self];
    
    self.jumpUrl = @"";
    _pedometer = [[CMPedometer alloc] init];

    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *fabu = [userDefault objectForKey:@"fabu"];
    if ([fabu isEqualToString:@"1"]) {
        
    }else {
        //弹
        MTPiaoLiuView *okView = [[MTPiaoLiuView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        okView.bgView.backgroundColor = KMainColor;
        okView.goButClick = ^(NSString *  s) {
            MTNewCardFirstVC *vc = GetViewControllerInStoryboard(@"Card", @"MTNewCardFirstVC");
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        
        MTYinjiView *yinjiView = [[MTYinjiView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        yinjiView.bgView.backgroundColor = KMainColor;
        yinjiView.goButClick = ^(NSString *  s) {
            [[UIApplication sharedApplication].keyWindow addSubview:okView];
        };
        [[UIApplication sharedApplication].keyWindow addSubview:yinjiView];
    }
    
    
    self.dingweiView = [[MTDingWeiView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
//    self.dingweiView.bgView.backgroundColor = KMainColor;
    self.dingweiView.goButClick = ^(NSString *  s) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if( [[UIApplication sharedApplication]canOpenURL:url] ) {
            [[UIApplication sharedApplication] openURL:url];
        }
    };
    [self.view addSubview:self.dingweiView];
    self.dingweiView.hidden = YES;

}
- (UIView*)UMSocialParentView:(UIView*)defaultSuperView
{
    return [UIApplication sharedApplication].keyWindow;
}
- (void)refreshMap:(NSNotification *)noti{
    NSDictionary *dic = noti.userInfo;
    NSURL *url = [NSURL URLWithString:[dic objectForKey:@"mapUrl"]];
    _mapView.styleURL = url;
    [_mapView reloadStyle:url];
    
//    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.mapUrl]];
}
//刷新按钮
- (void)setRefresh {
//    self.refreshBut = [HighLightButton new];
//    [self.mapView addSubview:self.refreshBut];
//    [self.refreshBut mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.bottom.mas_equalTo(-20);
//        make.width.mas_equalTo(44);
//        make.height.mas_equalTo(146);
//    }];
//    [self.refreshBut setImage:[UIImage imageNamed:@"地图操作"] forState:UIControlStateNormal];
    
    self.caozuoView = [UIView new];
    [self.mapView addSubview:self.caozuoView];
    [self.caozuoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.bottom.mas_equalTo(-20);
        make.width.mas_equalTo(44);
        make.height.mas_equalTo(188);
    }];
    UIImageView *img = [UIImageView new];
    [self.caozuoView addSubview:img];
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.bottom.mas_equalTo(0);
    }];
    img.image = [UIImage imageNamed:@"地图操作"];
    
    UIView *screen = [UIView new];
    [self.caozuoView addSubview:screen];
    [screen mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.bottom.mas_equalTo(0);
    }];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(createbgView)];
    screen.userInteractionEnabled=YES;
    [screen addGestureRecognizer:tap1];
    
    
    UIView *wei = [UIView new];
    [self.caozuoView addSubview:wei];
    [wei mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.mas_equalTo(0);
        make.top.mas_equalTo(48);
        make.height.mas_equalTo(48);
    }];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setDingWei)];
    wei.userInteractionEnabled=YES;
    [wei addGestureRecognizer:tap2];
    
    UIView *refresh = [UIView new];
    [self.caozuoView addSubview:refresh];
    [refresh mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(48);
        make.bottom.mas_equalTo(-48);

    }];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refreshClick)];
    refresh.userInteractionEnabled = YES;
    [refresh addGestureRecognizer:tap3];
    
    
    UIView *mypoint = [UIView new];
    [self.caozuoView addSubview:mypoint];
    [mypoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(48);
    }];
    UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mypointClick)];
    mypoint.userInteractionEnabled = YES;
    [mypoint addGestureRecognizer:tap4];
    
//    [self.refreshBut addTarget:self action:@selector(refreshClick) forControlEvents:UIControlEventTouchUpInside];
}
- (void)setStep {
    self.stepBut = [[HighLightButton alloc] initWithFrame:CGRectMake(0, 0, 48, 48)];
    [[UIApplication sharedApplication].keyWindow addSubview:self.stepBut];
    
    [self.stepBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(8+StatusHeight+20);
        make.width.mas_equalTo(48);
        make.height.mas_equalTo(48);
    }];
    [self.stepBut setImage:[UIImage imageNamed:@"计步器"] forState:UIControlStateNormal];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.stepBut];
    [self.stepBut addTarget:self action:@selector(pushStep) forControlEvents:UIControlEventTouchUpInside];
}
- (void)setPiaoliu {
    self.piaoliuBut = [[HighLightButton alloc] initWithFrame:CGRectMake(0, 0, 47, 43)];
    [self.mapView addSubview:self.piaoliuBut];
    
    [self.piaoliuBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(-30);
        make.width.mas_equalTo(57);
        make.height.mas_equalTo(57);
    }];
    [self.piaoliuBut setImage:[UIImage imageNamed:@"地图印记"] forState:UIControlStateNormal];
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.stepBut];
    [self.piaoliuBut addTarget:self action:@selector(piaoliuClick) forControlEvents:UIControlEventTouchUpInside];
}
//定位自己的点
- (void)setDingWei {
    [_mapView setCenterCoordinate:self.coordinate
                       zoomLevel:14
                        animated:NO];
}
- (void)piaoliuClick {
    WNImagePicker *pickerVC  = [[WNImagePicker alloc] initWithNibName:@"WNImagePicker" bundle:[NSBundle mainBundle]];
    pickerVC.delegate = self;
    //    BasicNavigationController *navVC = [[BasicNavigationController alloc]initWithRootViewController:pickerVC];
    UINavigationController *navVC = [[UINavigationController alloc]initWithRootViewController:pickerVC];
    [navVC.navigationBar setBackgroundImage:[UIImage imageWithColor:KBlackColor] forBarPosition:UIBarPositionAny
                                 barMetrics:UIBarMetricsDefault];
    //            [navVC.navigationBar setShadowImage:[UIImage new]];
    //            navVC.navigationBar.barTintColor = KWhiteColor;
    navVC.navigationBar.translucent = NO;
    // 设置导航栏默认的背景颜色
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:KBlackColor];
    // 设置导航栏所有按钮的默认颜色
    [WRNavigationBar wr_setDefaultNavBarTitleColor:KWhiteColor];
    
    [self presentViewController:navVC animated:YES completion:nil];
//    MTNewCardFirstVC *vc = GetViewControllerInStoryboard(@"Card", @"MTNewCardFirstVC");
//    [self.navigationController pushViewController:vc animated:YES];
}
//跳转步数
- (void)pushStep {
    MTStepVC *vc = GetViewControllerInStoryboard(@"Mine", @"MTStepVC");
    [self.navigationController pushViewController:vc animated:YES];
}
//刷新
- (void)refreshClick {
     [self updateUserLocation];
}
//只看自己的点
- (void)mypointClick {
    [self.mapView removeAnnotations:self.yinjipointArr];
    
    [self.mapView addAnnotations:self.myyinjipointArr];
}

- (void)updateUserLocation {
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            [self getInfo];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc updUsersInfolng:[NSString stringWithFormat:@"%f",self.coordinate.longitude] lat:[NSString stringWithFormat:@"%f",self.coordinate.latitude]];
    
}
- (void)getInfo {
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            NSArray *storyList = [data objectForKey:@"storyList"];
            

            NSMutableArray * list = [[NSMutableArray alloc] init];
            for ( NSDictionary*   dic in storyList)
            {
                FindModel * model = [[FindModel alloc] initWithDictionary:dic error:nil];
                 [list addObject:model];
            }
            self.dataArr = list;
            
            NSArray *imprintList = [data objectForKey:@"imprintList"];
            NSMutableArray * list2 = [[NSMutableArray alloc] init];
            for ( NSDictionary*   dic in imprintList)
            {
                YinjiModel * model = [[YinjiModel alloc] initWithDictionary:dic error:nil];
                [list2 addObject:model];
            }
            self.yinjiArr = list2;
            
            
            [self.mapView removeAnnotations:self.pointArr];
            [self.mapView removeAnnotations:self.yinjipointArr];
            [self.mapView removeAnnotations:self.myyinjipointArr];

            self.pointArr = [NSMutableArray new];
            for (FindModel *md in self.dataArr) {
                MyCustomPointAnnotation *pointAnnotation = [[MyCustomPointAnnotation alloc] init];
                pointAnnotation.model = md;
                pointAnnotation.willUseImage = YES;
                pointAnnotation.coordinate = CLLocationCoordinate2DMake([[NSString stringWithFormat:@"%@",md.lat] doubleValue], [[NSString stringWithFormat:@"%@",md.lng] doubleValue]);
               
                [self.pointArr addObject:pointAnnotation];

                Message *msg =  [[Message alloc] init];
                msg.userId =[NSString stringWithFormat:@"met_%@",md.createUsersId];
                msg.username = [NSString stringWithFormat:@"%@", md.nickName];
                msg.headImageUrl = [NSString stringWithFormat:@"%@",md.portraitMap];
                [Message insertObject:msg];
            }
            
            self.yinjipointArr = [NSMutableArray new];
            self.myyinjipointArr = [NSMutableArray new];
            for (YinjiModel *md in self.yinjiArr) {
                MyCustomYinjiPointAnnotation *pointAnnotation = [[MyCustomYinjiPointAnnotation alloc] init];
                pointAnnotation.model = md;
                pointAnnotation.willUseImage = YES;
                pointAnnotation.coordinate = CLLocationCoordinate2DMake([[NSString stringWithFormat:@"%@",md.lat] doubleValue], [[NSString stringWithFormat:@"%@",md.lng] doubleValue]);
                [self.yinjipointArr addObject:pointAnnotation];
                if ([[NSString stringWithFormat:@"%@",md.usersId] isEqualToString:[NSString stringWithFormat:@"%@",KUSER.usersId]]) {
                    [self.myyinjipointArr addObject:pointAnnotation];
                }
            }
            
            [self.mapView addAnnotations:self.yinjipointArr];
            [self.mapView addAnnotations:self.pointArr];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findIndexStorylat:[NSString stringWithFormat:@"%f",self.coordinate.latitude] lng:[NSString stringWithFormat:@"%f",self.coordinate.longitude]];
}

- (void)pushPhoto {
    MTNewCardFirstVC *vc = GetViewControllerInStoryboard(@"Card", @"MTNewCardFirstVC");
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark -- WNImagePickerDelegate
- (void)getCutImage:(NSMutableArray *)imageArr controller:(WNImagePicker *)vc
{
    [vc.navigationController dismissViewControllerAnimated:NO completion:nil];
//    ImageEditVC *editVC = [[ImageEditVC alloc]init];
    MTPubMarkVC *pubvc = [[MTPubMarkVC alloc]init];
//    editVC.image = image;
    pubvc.photoArr = imageArr;
    [self.navigationController pushViewController:pubvc animated:YES];
}

- (void)onCancel:(WNImagePicker *)vc
{
    [vc.navigationController dismissViewControllerAnimated:YES completion:nil];
}
- (void)pushCard {
    MTNewCardFirstVC *vc = GetViewControllerInStoryboard(@"Card", @"MTNewCardFirstVC");
    [self.navigationController pushViewController:vc animated:YES];
   
}
- (void)CreateNav {
    
}
- (void)customNavItem {
    self.navigationItem.title = @"发现卡牌";
    RightPhotoButton *rightBtn = [[RightPhotoButton alloc] init];
    [rightBtn setImage:[UIImage imageNamed:@"xia"] forState:UIControlStateNormal];
    [rightBtn setTitle:@"筛选  " forState:UIControlStateNormal];
    [rightBtn setTitleColor:KBlackColor forState:UIControlStateNormal];
    rightBtn.titleLabel.font = SBFONT(15);
    [rightBtn setImage:[UIImage imageNamed:@"xia"] forState:UIControlStateHighlighted];
    [rightBtn addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 80, 50);
    [right addTarget:self action:@selector(done) forControlEvents:UIControlEventTouchUpInside];
    right.adjustsImageWhenHighlighted = NO;
    right.titleLabel.font = SBFONT(15);
    [right setTitle:@"车票" forState:UIControlStateNormal];
    [right setTitleColor:KBlackColor forState:UIControlStateNormal];
    [right setTitleEdgeInsets:UIEdgeInsetsMake(0,-40,0, 0)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:right];
}
//点击车票
- (void)done {
    MTTicketVC *vc =  GetViewControllerInStoryboard(@"Mine", @"MTTicketVC");
    [self.navigationController pushViewController:vc animated:YES];

}
- (void)rightAction {
    [self createbgView];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置导航栏默认的背景颜色
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:KWhiteColor];
    [WRNavigationBar wr_setDefaultNavBarTitleColor:KBlackColor];
    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
    
    [manager startUpdatingLocation];

//    [self checkbushu];
    [self reloadData];
    [self.userImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.portraitMap]] placeholderImage:[UIImage imageNamed:@"椭圆 1"]];

    
    
}
- (void)reloadData{
    if ([CMPedometer isStepCountingAvailable]) {// start  end
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate *now = [NSDate date];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
        NSDate *startDate = [calendar dateFromComponents:components];
        NSLog(@"++++++++++++++++ :%@",startDate);
        [_pedometer startPedometerUpdatesFromDate:startDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
            if (error)
            {
                NSLog(@"error===%@",error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.stepBut setImage:[UIImage imageNamed:@"计步器"] forState:UIControlStateNormal];
                });
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.stepBut setImage:[UIImage imageNamed:@"计步器1"] forState:UIControlStateNormal];
                });
            }
        }];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.stepBut setImage:[UIImage imageNamed:@"计步器"] forState:UIControlStateNormal];
        });
    }
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSUserDefaults *dataUser = [NSUserDefaults standardUserDefaults];
    [dataUser setObject:@"0" forKey:@"tab"];
    self.stepBut.hidden = NO;

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.stepBut.hidden = YES;

//    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:NO]
}

- (void)createbgView {
    self.bgView = [UIView new];
    [[UIApplication sharedApplication].keyWindow addSubview:self.bgView];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    UIView *bg = [[UIView alloc]init];
    bg.backgroundColor = [UIColor blackColor];
    bg.alpha = 0.6;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removebgView)];
    [bg addGestureRecognizer:tap];
    [self.bgView addSubview:bg];
    [bg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    MTScreenView *screenView = [[MTScreenView alloc]initWithFrame:CGRectMake(0, kScreenHeight-BottomHeight-126, kScreenWidth, 136+BottomHeight)];
    //筛选点击了
    MJWeakSelf
    screenView.screenClick = ^(NSString *  num) {
        NSUserDefaults *dataUser = [NSUserDefaults standardUserDefaults];
        [dataUser setObject:num forKey:@"sex"];
        [dataUser synchronize];
        [weakSelf removebgView];
        [weakSelf updateUserLocation];
    };
    [self.bgView addSubview:screenView];
    
}
- (void)removebgView {
    [self.bgView removeFromSuperview];
}

- (void)homeClick{
//    [self removebgView2];
//    MTUserInfoVC *vc = [[MTUserInfoVC alloc] init];
    MTNewUserInfoVC *vc = [[MTNewUserInfoVC alloc] init];
    vc.userId = [NSString stringWithFormat:@"%@",self.chooseModel.createUsersId];
    vc.isMutual = [NSString stringWithFormat:@"%@",self.chooseModel.isMutual];
    vc.createType = [NSString stringWithFormat:@"%@",self.chooseModel.createType];
    vc.nickname = [NSString stringWithFormat:@"%@",self.chooseModel.nickName];
    [self.navigationController pushViewController:vc animated:YES];
}
//取消选中
- (void)back {
    [self.mapView deselectAnnotation:self.chooseAnnotation animated:YES];
    [_mapView setCenterCoordinate:self.coordinate
                        zoomLevel:14
                         animated:NO];
}

- (void)siliaoClick {
    ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:[NSString stringWithFormat:@"met_%@",self.chooseModel.createUsersId] conversationType:EMConversationTypeChat];
    chatController.title =  self.chooseModel.nickName;
    chatController.username =  self.chooseModel.nickName;
    chatController.userid =  [NSString stringWithFormat:@"%@",self.chooseModel.createUsersId];
    [self.navigationController pushViewController:chatController animated:YES];
}

//------------------------地图-------------------

#pragma mark MGLMapViewDelegate

- (void)mapViewDidFinishLoadingMap:(MGLMapView *)mapView {
    ///地图加载完成时加载大头针
    [self updateUserLocation];
}

- (MGLAnnotationView *)mapView:(MGLMapView *)mapView viewForAnnotation:(id<MGLAnnotation>)annotation {
    if ([annotation isKindOfClass:[MGLUserLocation class]]) {
        MGLUserLocationAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView"];
        if (annotationView == nil) {
            annotationView = [[MGLUserLocationAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MGLAnnotationView"];
            [annotationView setFrame:CGRectMake(0, 0, 72, 72)];
//            [annotationView setBackgroundColor:[UIColor redColor]];
            
            UIImageView *bg = [UIImageView new];
            bg.image = [UIImage imageNamed:@"椭圆 1"];
            [annotationView addSubview:bg];
            [bg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.right.bottom.mas_equalTo(0);
            }];
            
            self.userImage = [UIImageView new];
            [self.userImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.portraitMap]] placeholderImage:[UIImage imageNamed:@"椭圆 1"]];

            [annotationView addSubview:self.userImage];
            [self.userImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.mas_equalTo(8);
                make.right.bottom.mas_equalTo(-8);
            }];
            self.userImage.layer.cornerRadius = 28.f;
            self.userImage.layer.masksToBounds= YES;
          
            
            
            
            annotationView.layer.cornerRadius = 36.f;
            annotationView.layer.masksToBounds= YES;
            
            
//            annotationView.layer.borderColor  = [UIColor blackColor].CGColor;
//            annotationView.layer.borderWidth  = 1.f;
//            annotationView.layer.borderColor  = [UIColor whiteColor].CGColor;
//            annotationView.layer.borderWidth  = 5.f;
        }
        return annotationView;
        
        return nil;
    }
    if (![annotation isKindOfClass:[MGLPointAnnotation class]]) {
        return nil;
    }
    if ([annotation isKindOfClass:[MyCustomPointAnnotation class]]) {
        MyCustomPointAnnotation *castAnnotation = (MyCustomPointAnnotation *)annotation;
        
//        MGLCustomAnnotationView *annotationView = (MGLCustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView"];
//        MGLCustomAnnotationView *annotationView = [[MGLCustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MGLAnnotationView"];
//        [mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView"];
        FindModel *model =  castAnnotation.model;
        
//        if (annotationView == nil) {
       MGLCustomAnnotationView * annotationView = [[MGLCustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
//            annotationView = (MGLCustomAnnotationView*) annotationView;
            [annotationView setFrame:CGRectMake(0, 0, 44, 44)];
            
            annotationView.bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
            annotationView.bg.image = [UIImage imageNamed:@"玩家"];
            [annotationView addSubview:annotationView.bg];
//            [bg mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.right.top.bottom.mas_equalTo(0);
//            }];
            annotationView.img = [[UIImageView alloc] initWithFrame:CGRectMake(6, 6, 32, 32)];
//            [img mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.top.left.mas_equalTo(6);
//                make.right.bottom.mas_equalTo(-6);
//            }];
            [annotationView addSubview:annotationView.img];

            annotationView.img.contentMode = UIViewContentModeScaleAspectFill;
            [annotationView.img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",model.portraitMap]] placeholderImage:[UIImage imageNamed:@"椭圆 1 拷贝 7"]];
//            annotationView.img.layer.cornerRadius = 16;
//            annotationView.img.layer.masksToBounds= YES;
//            annotationView.layer.cornerRadius = 22;
//            annotationView.layer.masksToBounds  = YES;
        
        CGFloat radius = 16; // 圆角大小
        UIRectCorner corner = UIRectCornerAllCorners; // 圆角位置，全部位置
        UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:annotationView.img.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(radius, radius)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = annotationView.img.bounds;
        maskLayer.path = path.CGPath;
        annotationView.img.layer.mask = maskLayer;
        
        
        
        //            annotationView.layer.cornerRadius = 36.f;
        //            annotationView.layer.masksToBounds= YES;
        
        CGFloat radius2 = 22; // 圆角大小
        UIRectCorner corner2 = UIRectCornerAllCorners; // 圆角位置，全部位置
        UIBezierPath * path2 = [UIBezierPath bezierPathWithRoundedRect:annotationView.bounds byRoundingCorners:corner2 cornerRadii:CGSizeMake(radius2, radius2)];
        CAShapeLayer *maskLayer2 = [[CAShapeLayer alloc] init];
        maskLayer2.frame = annotationView.bounds;
        maskLayer2.path = path2.CGPath;
        annotationView.layer.mask = maskLayer2;
        
        
        
//        }
        return annotationView;

    }
    if ([annotation isKindOfClass:[MyCustomYinjiPointAnnotation class]]) {
        MyCustomYinjiPointAnnotation *castAnnotation = (MyCustomYinjiPointAnnotation *)annotation;
        
        MGLCustomAnnotationView *annotationView = (MGLCustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView2"];
//        YinjiModel *model =  castAnnotation.model;
        if (annotationView == nil) {
            annotationView = [[MGLCustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MGLAnnotationView2"];
            //            annotationView = (MGLCustomAnnotationView*) annotationView;
            [annotationView setFrame:CGRectMake(0, 0, 19, 18)];
            annotationView.yinji = @"1";
            
            annotationView.bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 19, 18)];
            annotationView.bg.image = [UIImage imageNamed:@"yinji"];
            [annotationView addSubview:annotationView.bg];
        }
        return annotationView;
        
    }
    
    MGLAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView"];
    if (annotationView == nil) {
        annotationView = [[MGLAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MGLAnnotationView"];
        [annotationView setFrame:CGRectMake(0, 0, 60, 60)];
        [annotationView setBackgroundColor:[UIColor redColor]];
              
        annotationView.layer.cornerRadius = 10.f;
        annotationView.layer.masksToBounds= YES;
        annotationView.layer.borderColor  = [UIColor whiteColor].CGColor;
        annotationView.layer.borderWidth  = 5.f;
    }
    return annotationView;
}
- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation {
    if ([annotation isKindOfClass:[MGLUserLocation class]]) {
        return nil;
    }
    if ([annotation isKindOfClass:[MyCustomPointAnnotation class]]) {
        MyCustomPointAnnotation *castAnnotation = (MyCustomPointAnnotation *)annotation;
        if (!castAnnotation.willUseImage) {
            return nil;
        }
    }
    MyCustomPointAnnotation *castAnnotation = (MyCustomPointAnnotation *)annotation;
    MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:@"camera"];

    if ([castAnnotation.userId isEqualToString:@"1"]) {
        UIImage *image = [UIImage imageNamed:@"发现"];
        image = [image imageWithAlignmentRectInsets:UIEdgeInsetsMake(0, 0, image.size.height/2, 0)];
        
        annotationImage = [MGLAnnotationImage annotationImageWithImage:image reuseIdentifier:@"camera2"];
    }else {
        UIImage *image = [UIImage imageNamed:@"椭圆 1 拷贝 7"];
        image = [image imageWithAlignmentRectInsets:UIEdgeInsetsMake(0, 0, image.size.height/2, 0)];
        annotationImage = [MGLAnnotationImage annotationImageWithImage:image reuseIdentifier:@"camera"];
    }
    return annotationImage;
}

///是否显示气泡
-(BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id<MGLAnnotation>)annotation {
    return NO;
}
///完成加载大头针
- (void)mapView:(MGLMapView *)mapView didAddAnnotationViews:(NSArray<MGLAnnotationView *> *)annotationViews {
//    [mapView showAnnotations:self.annotationsArray edgePadding:UIEdgeInsetsMake(100, 50, 100, 50) animated:YES];
}


//选中大头针
- (void)mapView:(MGLMapView *)mapView didSelectAnnotation:(id<MGLAnnotation>)annotation {
    if ([annotation isKindOfClass:[MyCustomPointAnnotation class]]) {
        
        MyCustomPointAnnotation *castAnnotation = (MyCustomPointAnnotation *)annotation;
        self.chooseAnnotation = castAnnotation;

       
        MTFindOtherVC *vc = [[MTFindOtherVC alloc] init];
        vc.chooseModel = castAnnotation.model;
        self.chooseModel = castAnnotation.model;
        vc.home = ^(NSString *  s) {
            [self homeClick];
        };
        vc.liaota = ^(NSDictionary *  data) {
//            [self liaotaClick];
            if ([[NSString stringWithFormat:@"%@",self.chooseModel.createType] isEqualToString:@"1"]) {
                //用户
                MTQuestionAnswerVC *vc = [[MTQuestionAnswerVC alloc] init];
                vc.dataArr = [data objectForKey:@"questionList"];
                vc.leftName = [NSString stringWithFormat:@"%@",self.chooseModel.nickName];
                vc.rightName =[NSString stringWithFormat:@"%@",KUSER.nickName] ;
                vc.storyId = [NSString stringWithFormat:@"%@",self.chooseModel.storyId];
                vc.sex = [NSString stringWithFormat:@"%@",self.chooseModel.sex];
                
                vc.storyVersion = [NSString stringWithFormat:@"%@",self.chooseModel.storyVersion];
                vc.createUsersId = [NSString stringWithFormat:@"%@",self.chooseModel.createUsersId];
                vc.hasAnswer = ^(NSString * num) {
                    [self updateUserLocation];

//                    [self.mapView deselectAnnotation:self.chooseAnnotation animated:YES];
//                    [self.mapView removeAnnotation:self.chooseAnnotation];
                };
                
                vc.leftUrl = [NSString stringWithFormat:@"%@",[data objectForKey:@"portraitIm"]];
                vc.rightUrl = [NSString stringWithFormat:@"%@",KUSER.portraitIm];
                vc.sceneUrl = [NSString stringWithFormat:@"%@",[data objectForKey:@"sceneUrl"]];
                
                [self.navigationController pushViewController:vc animated:YES];
            }else {
                MTQuestionNpcAnswerVC *vc = [[MTQuestionNpcAnswerVC alloc] init];
                vc.dataArr = [data objectForKey:@"questionList"];
                vc.leftName = self.chooseModel.nickName;
                vc.rightName = KUSER.nickName;
                vc.storyId = self.chooseModel.storyId;
                vc.storyVersion = self.chooseModel.storyVersion;
                vc.createUsersId = self.chooseModel.createUsersId;
                
                vc.leftUrl = [NSString stringWithFormat:@"%@",[data objectForKey:@"portraitIm"]];
                vc.rightUrl = [NSString stringWithFormat:@"%@",KUSER.portraitIm];
                vc.sceneUrl = [NSString stringWithFormat:@"%@",[data objectForKey:@"sceneUrl"]];
                vc.sex = [NSString stringWithFormat:@"%@",[data objectForKey:@"sex"]];

                vc.hasAnswer = ^(NSString * num) {
                    [self updateUserLocation];

//                    [self.mapView deselectAnnotation:self.chooseAnnotation animated:YES];
//
//                    [self.mapView removeAnnotation:self.chooseAnnotation];
                };
                [self.navigationController pushViewController:vc animated:YES];
            }
        };
        vc.siliao = ^(NSString *  s) {
            [self siliaoClick];
        };
        [self.mapView deselectAnnotation:annotation animated:NO];
        [self presentViewController:vc animated:YES completion:nil];
        return;
        
//        [self createFindView:castAnnotation.model];
//        MGLCustomAnnotationView *annotationView =  (MGLCustomAnnotationView *)[mapView viewForAnnotation:castAnnotation];
//        [annotationView setFrame:CGRectMake(0, 0, 72, 72)];
//        [annotationView.bg setFrame:CGRectMake(0, 0, 72, 72)];
//        [annotationView.img setFrame:CGRectMake(8, 8, 56, 56)];
//        annotationView.img.layer.cornerRadius = 28.f;
//        annotationView.img.layer.masksToBounds= YES;
//        annotationView.layer.cornerRadius = 36.f;
//        annotationView.layer.masksToBounds  = YES;
//
//        [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(castAnnotation.coordinate.latitude,castAnnotation.coordinate.longitude)
//                           zoomLevel:14
//                            animated:YES];
//        return ;
    }else  if ([annotation isKindOfClass:[MyCustomYinjiPointAnnotation class]]) {
        MyCustomYinjiPointAnnotation *castAnnotation = (MyCustomYinjiPointAnnotation *)annotation;
//        MTMarkDetailVC *vc = [[MTMarkDetailVC alloc] init];
//        vc.model = castAnnotation.model;
        [self.mapView deselectAnnotation:annotation animated:NO];
//        [self.navigationController pushViewController:vc animated:YES];
//        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        AccountService *acc = [AccountService getObject];
        acc.httpRequestResultBlock = ^(id data,int code){
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (code == 1) {
                MTMarkDetailVC *vc = [[MTMarkDetailVC alloc] init];
                vc.model = data;
                [self.navigationController pushViewController:vc animated:YES];
            }else {
                [self.view maketishiToast:data];
            }
        };
        [acc imprintFind:castAnnotation.model.imprintId];
    }
}
//取消选中
- (void)mapView:(MGLMapView *)mapView didDeselectAnnotation:(id<MGLAnnotation>)annotation {

}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *loctaion = [locations firstObject];
    self.coordinate = loctaion.coordinate;
    [manager stopUpdatingLocation];

    if ([NSString stringWithFormat:@"%f",self.coordinate.longitude].length > 0) {
        self.dingweiView.hidden = YES;
    }else {
        self.dingweiView.hidden = NO;
    }
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//    });
}

//-------------------------地图---------------------






- (void) yaoqing {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            if ([[NSString stringWithFormat:@"%@",[data objectForKey:@"model"]]isEqualToString:@"1"]) {
            }else {
                //邀请链接
                NSString *url = [NSString stringWithFormat:@"%@",[data objectForKey:@"content"]];
                self.jumpUrl = url;
                [self shareClick];
            }
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findOthers:@"10"];
}


- (void)shareClick {
    //显示分享面板
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        [self shareImageAndTextToPlatformType:platformType];
    }];
}
- (void)shareImageAndTextToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享标识
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //设置文本
    messageObject.text = @"";
    
    MTYaoQingView *yao = [[MTYaoQingView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
    yao.codeView.image = [self createCode];
    
    UIImage *img = [self makeImageWithView:yao withSize:CGSizeMake(375, 667)];
    
    //创建图片内容对象
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图，则设置缩略图
    shareObject.thumbImage = [UIImage imageNamed:@"AppIcon"];
    [shareObject setShareImage:img];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}

- (UIImage *)createCode{
    //
    NSArray *filters = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
    NSLog(@"%@",filters);
    //二维码过滤器
    CIFilter *qrImageFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //设置过滤器默认属性
    [qrImageFilter setDefaults];
    //将字符串转换成 NSdata (虽然二维码本质上是 字符串,但是这里需要转换,不转换就崩溃)
    // 字符串可以随意换成网址等
    NSString *url = self.jumpUrl;
    
    NSData *qrImageData = [url dataUsingEncoding:NSUTF8StringEncoding];
    //我们可以打印,看过滤器的 输入属性.这样我们才知道给谁赋值
    NSLog(@"%@",qrImageFilter.inputKeys);
    //设置过滤器的 输入值 ,KVC赋值
    [qrImageFilter setValue:qrImageData forKey:@"inputMessage"];
    //取出图片
    CIImage *qrImage = [qrImageFilter outputImage];
    //但是图片 发现有的小 (27,27),我们需要放大..我们进去CIImage 内部看属性
    qrImage = [qrImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)];
    //转成 UI的 类型
    UIImage *qrUIImage = [UIImage imageWithCIImage:qrImage];
    //----------------给 二维码 中间增加一个 自定义图片----------------
    //开启绘图,获取图形上下文 (上下文的大小,就是二维码的大小)
    UIGraphicsBeginImageContext(qrUIImage.size);
    //把二维码图片画上去. (这里是以,图形上下文,左上角为 (0,0)点)
    [qrUIImage drawInRect:CGRectMake(0, 0, qrUIImage.size.width, qrUIImage.size.height)];
    //再把小图片画上去
    UIImage *sImage = [UIImage imageNamed:@"icon108"];
    CGFloat sImageW = 100;
    CGFloat sImageH= sImageW;
    CGFloat sImageX = (qrUIImage.size.width - sImageW) * 0.5;
    CGFloat sImgaeY = (qrUIImage.size.height - sImageH) * 0.5;
    [sImage drawInRect:CGRectMake(sImageX, sImgaeY, sImageW, sImageH)];
    //获取当前画得的这张图片
    UIImage *finalyImage = UIGraphicsGetImageFromCurrentImageContext();
    //关闭图形上下文
    UIGraphicsEndImageContext();
    //设置图片
    return  finalyImage;
}

- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}



@end
